package com.imti.externalstoragedemo;

import android.Manifest;
import android.Manifest.permission;
import android.os.Environment;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.tbruyelle.rxpermissions3.RxPermissions;
import io.reactivex.rxjava3.functions.Consumer;
import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity
{

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //涉及用户隐私的危险权限动态请求用户授权
        RxPermissions rxPermissions = new RxPermissions(this);

        //判断是否同意某个权限
        if (!rxPermissions.isGranted(
            android.Manifest.permission.READ_EXTERNAL_STORAGE))
        {
            rxPermissions.request(
                android.Manifest.permission.READ_EXTERNAL_STORAGE,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>()
                {
                    //granted 用户是否同意授权权限
                    @Override
                    public void accept(Boolean granted) throws Throwable
                    {
                        //granted 为true时即用户授权成功
                        if (granted)
                        {
                            initView();
                        }
                    }
                });
        } else
        {
            try
            {
                initView();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }

    }

    private void initView() throws IOException
    {
        //1.判断外部存储是否正常挂载
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
        {
            //2.获取外部存储目录的根目录路径
            File rootDir = Environment.getExternalStorageDirectory();
            String rootPath = rootDir.getCanonicalPath();

            //外部存储的路径不是固定的，
            //具体会根据不同厂商版本，不同系统版本变化而变化
            //可能的外部存储根目录
            // /data/media/0/
            // /mnt/sdcard/
            // /sdcard/
            // /storage/emulated/0/ 模拟器专用

            Log.d(TAG, "外部存储根目录路径：" + rootPath);

            File extStorageFile = new File(
                rootPath + "/Download/external_file.txt");

            //读取文件内容
        }
    }
}